import { createRouter, createWebHistory } from 'vue-router'


const routes = [{
    path: '/',
    redirect: '/home/index'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "login" */ '@/views/login')
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    component: () => import(/* webpackChunkName: "detail" */ '@/views/detail')
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import(/* webpackChunkName: "home" */ '@/views/home'),
    children: [{
      path: '/home/car',
      name: 'Car',
      component: () => import(/* webpackChunkName: "car" */ '@/views/home/car'),
      // 路由元信息
      meta: {
        requireLogin: true
      }
    },{
      path: '/home/index',
      name: 'Index',
      component: () => import(/* webpackChunkName: "index" */ '@/views/home/index/index.vue'),
    },{
      path: '/home/my',
      name: 'My',
      component: () => import(/* webpackChunkName: "my" */ '@/views/home/my'),
       // 路由元信息
       meta: {
        requireLogin: true
      }
    },{
      path: '/home/classify',
      name: 'Classify',
      component: () => import(/* webpackChunkName: "classify" */ '@/views/home/classify'),
    }]
  },
  {
    path: '/search',
    name: 'Search',
    component: () => import(/* webpackChunkName: "search" */ '@/views/search')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotMatch',
    component: () => import(/* webpackChunkName: "404" */ '@/views/404')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})


// 全局路由前置守卫
// 当路由发生导航， 前置最先执行
router.beforeEach((to, from, next) => {
  // to ： 即将要进入的目标路由
  // from : 当前导航正要离开的路由
  // next : 钩子函数
      //  next()  正常跳转
      //  next(路由)  重定向进入的路由页面

  // Vue3 return false 取消导航   return true  正常导航
  console.log('进入');
  console.log(to);
  console.log('离开');
  console.log(from);

  // 我们要跳转的页面需要登录   但是我们没有登录
  if(to.meta.requireLogin && !localStorage.getItem('token')) {
    // 跳转登录页面
    next({ name: 'Login' })
  } else {
    // 否则正常导航
    next()
  }


  // return true
})

export default router
